import axios from 'axios'
import { ElMessageBox } from 'element-plus' // 改为引入 ElMessageBox
import router from '@/router'

const baseURL = 'http://localhost:8888'
const instance = axios.create({ baseURL })

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const result = response.data
    if (result.message.includes('The Token has expired on')) {
      // 清除过期 token
      localStorage.removeItem('token')
      localStorage.removeItem('tokenStartTime')
      localStorage.removeItem('userInfo')

      // 使用确认弹窗替代错误提示
      ElMessageBox.confirm('登录已过期，请重新登录', '提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确认后跳转登录页
        router.push('/login')
      }).catch(() => {
        // 点击取消不做操作
      })

      return Promise.reject('The Token has expired on')
    }
    if (result.code !== 200) {
      return Promise.reject(result.message)
    }
    return result
  }
)

export default instance
